﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

/// <summary>
///PaginationTools 的摘要说明
/// </summary>
public class PaginationTools
{
	public PaginationTools()
	{
		//
		//TODO: 在此处添加构造函数逻辑
		//
	}

    /// <summary>
    /// 返回sql Select数据的分页语句
    /// </summary>
    public static string FormatPaginationSelectString(string selectString, string rownumberColumnName, int rows, int page)
    {
        string pageStr = "";
        if (page != 0) pageStr = string.Format("and ({2}>{0} and {2}<={1})", rows * (page - 1), rows * page, rownumberColumnName);
        string temp = selectString.ToLower();
        int index = temp.IndexOf("select") + 6;
        temp=selectString.Substring(index, selectString.Length - (index + 1));
        return string.Format("select * from(select (ROW_NUMBER() OVER({3})) as {0} , {1} )cc where 1=1 {2}", rownumberColumnName, temp, pageStr, getOrderCondition(temp));

    }

    public static string getOrderCondition(string selectStr)
    {
        string temp = selectStr.ToLower();
        int index = temp.IndexOf("order");
      return   selectStr.Substring(index, selectStr.Length - index);
    }

    /// <summary>
    /// 返回sql Select数据的Count语句 ，如 "select a,b,c, form dd where aa=1 order by b",将返回 "select count(*) form dd where aa=1"
    /// </summary>
    public static string FormatPaginationCountString(string selectString)
    {
      
        string temp = selectString.ToLower();
        int index = temp.IndexOf("from") + 4;
        selectString=selectString.Substring(index, selectString.Length - (index + 1));
        temp=selectString.ToLower();
        index=temp.IndexOf("order");
        selectString = selectString.Substring(0, index);
        return string.Format("select count(*) from {0} ", selectString);

    }

    public static string FormatPaginationSelectString(string selectString, string rownumberColumnName, string rows, string page)
    {
        int rowsInt=0;
        int pageInt=0;
        int.TryParse(rows,out rowsInt );
        int.TryParse(page,out pageInt );
        return  FormatPaginationSelectString( selectString,  rownumberColumnName,  rowsInt,  pageInt);
    }
}
